<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 *
 * @abstract 维修项管理
 * @author zxj
 *
 */
class Product_repair_item extends MY_Controller {
	private $t_pRepairItem = 'mt_product_repair_item';
    private $role = '';
    function __construct() {
        parent::__construct();
        $this->role = $this->users['role'];
        if($this->role != 'admin'){
           // show_error('invalid access');
        }
        $this->load->model('product_sap_model','sapModel');
    }


	/**
	 * 列表页
	 */
	function index()
    {
        //获取表单数据
        $data = $formField = gp();
        //查询条件
        $where = $whereLike = array();
        //默认select设置
        $optGrade[$formField['grade']] = 'selected';
        $data['optGrade'] = $optGrade;//维修级别
        $optCategory[$formField['category']] = 'selected';
        $data['optCategory'] = $optCategory;//产品类型
        $optBrand[$formField['brand_id']]='selected';
        $data['optBrand'] = $optBrand;//产品品牌
        $optModel[$formField['model_id']]='selected';
        $data['optModel'] = $optModel;//产品型号
        $optDefault[$formField['isDefault']]='selected';
        $data['optDefault'] = $optDefault;//是否默认
        //url GET参数拼接
        $searchStr = 'orders/Product_repair_item/index/?';
        $keyword = trim($formField['keyword']);
        if($keyword){
            if (preg_match('/[\x7f-\xff]/', $keyword)) {
                $whereLike['name_ch'] = $keyword;
            }else{
                $whereLike['name_en'] = $keyword;
            }
            $searchStr .= 'keyword='.$keyword;
        }
        //维修级别
        if ($formField['grade']){
            $where['grade'] = $formField['grade'];
            $searchStr .= '&grade=' . $formField['grade'];
        }
        //产品类型
        if ($formField['category']){
            $category=explode('_',$formField['category']);
            $where['category'] = $category[0];
            $searchStr .= '&category=' . $formField['category'];
        }
        //产品品牌
        if ($formField['brand_id']){
            $where['brand_id'] = $formField['brand_id'];
            $searchStr .= '&brand_id=' . $formField['brand_id'];
        }
        //产品型号
        if ($formField['model_id']){
            $where['model_id'] = $formField['model_id'];
            $searchStr .= '&model_id=' . $formField['model_id'];
        }
        //是否默认
        if ($formField['isDefault']){
            $where['isDefault'] = $formField['isDefault'];
            $searchStr .= '&isDefault=' . $formField['isDefault'];
        }
        //分页
        $this->load->library('pagination');
        $config['page_query_string'] = TRUE;
        $config['base_url'] = blang_url($searchStr);
        $config['total_rows'] = $this->common_model->countRows($this->t_pRepairItem, $where, '', $whereLike);
        $config['per_page'] = $data['outputExcel'] ? $config['total_rows'] : 20;
        $page = max(1, intval($data['page']));
        $config['uri_segment'] = config_item('enable_lang') ? 5 : 4;
        $slimit = ($page - 1) * $config['per_page'];
        $this->pagination->initialize($config);
        $dataList = $this->common_model->select($this->t_pRepairItem, $slimit, $config['per_page'], 'id asc', $where, '', $whereLike);
        $data['show_pages'] = $this->pagination->create_links();
        //重构数据
        $availableArr = array('delete','normal','disable');
        foreach ($dataList as $key => &$rs) {
            $rs['availableName'] = $availableArr[$rs['available']];
            $rs['isDefault'] = $rs['isDefault']?'Yes':'No';
            $gradeFirst = $this->common_model->selectFirst('mt_repair_grade', array('id' => $rs['grade']));
            $categoryFirst = $this->common_model->selectFirst('mt_product_category', array('id' => $rs['category']));
            $rs['gradeName'] = $gradeFirst['name_'.$this->curLang];
            $rs['categoryName'] = $categoryFirst['name_'.$this->curLang];
            $rs['add_time'] = date('Y-m-d H:i:s',$rs['add_time']);
        }
        unset($rs);
        $data['dataList'] = $dataList;
        //查询维修等级
        $gradeList = $this->common_model->selectall('mt_repair_grade');
        $data['gradeList'] = $gradeList;
        //查询产品类型
        $categoryList = $this->common_model->selectCustom('mt_product_category');
        $data['categoryList'] = $categoryList;
        //查询品牌
        $typeId=explode('_',$formField['category']);
        if($formField['brand_id']){
            $data['brandList']=$this->productClassData($typeId[1]);
        }
        //查询型号
        if($formField['model_id']){
            $data['modelList']=$this->productClassData($typeId[1],$formField['brand_id']);
        }
        if($this->debug){
            gsh_output($data);
        }
        //视图以及样式
        $data['curLang'] = $this->curLang;
        $this->load->view('defaults/product_repairItem_list', $data);
        $this->load->view('defaults/common/footer');
    }


    /**
     * 新增
     */
    function add() {
       $this->load->model('partner_model'); //加载合作商维修项
        //表单处理
        $data['post_type'] = __FUNCTION__;
        $formData = gp();
        if ($formData['submits']) {
            if(!$formData['name_en'] && !$formData['name_ch']){
                show_error('name not Null');
            }
            $inData = array();
            $fieldsList = $this->db->list_fields($this->t_pRepairItem);
            foreach ($formData as $key => $val) {
                if (($val || $val === '0') && in_array($key, $fieldsList)) {
                    $inData[$key] = $val;
                }
            }
            //是否默认
            if($inData['isDefault']){
                $this->common_model->update($this->t_pRepairItem, array('isDefault'=>0), array('category'=>$inData['category']));
            }
            if ($inData) {
                $inData['add_user'] = $this->users['account'];
                $inData['add_time'] = time();
                $category = explode('_',$formData['category']);
                $inData['category']=$category[0];
                $id = $this->common_model->insert($this->t_pRepairItem, $inData);
                //新增金额
                $siteList = $this->common_model->selectCustom('mt_service_center');
                foreach ($siteList as $row) {
                    $point_id = $row['id'];
                    $baseArr = array(
                        'merchant_price'=>$formData['merchant_price'.$point_id],
                        'individual_price'=>$formData['individual_price'.$point_id],
                        'brand_price'=>$formData['brand_price'.$point_id],
                        'site_id'=>$point_id,
                        'category_id'=>$category[0],
                        'brand_id'=>$formData['brand_id'],
                        'model_id'=>$formData['model_id'],
                        'grade'=>$formData['grade'],
                        'labor_id'=>$id
                    );
                    $this->common_model->insert('mt_base_price', $baseArr);
                    $this->partner_model->AddItemByBasic($baseArr, array('name_ch' => $formData['name_ch'], 'name_en' => $formData['name_en']));
                }
            }
            //调试信息
            if (!$this->debug) {
                redirect('orders/Product_repair_item/');
            }
        } else {
            //查询维修等级
            $gradeList = $this->common_model->selectall('mt_repair_grade');
            $data['gradeList'] = $gradeList;
            //查询产品类型
            $categoryList = $this->common_model->selectCustom('mt_product_category');
            $data['categoryList'] = $categoryList;
            //查询站点
            $siteLaborList = $this->common_model->selectCustom('mt_service_center');
            foreach ($siteLaborList as &$row) {
                $row['point_id'] = $row['id'];
            }
            unset($row);
            $data['siteLaborList'] = $siteLaborList;
            //views
            $data['curLang'] = $this->curLang;
            $this->load->view('defaults/product_repairItem_post', $data);
            $this->load->view('defaults/common/footer');
        }
    }



    /**
     * 修改
     * @param string $id
     */
    function edit($id = ''){
        //表单处理
        $data['post_type'] = __FUNCTION__;
        //接收数据
        $id = intval($id)?intval($id):gp('id');
        $repairItemFirst = $this->common_model->selectFirst($this->t_pRepairItem,array('id'=>$id));
        if(!$repairItemFirst){
            show_error('this id not found');
        }
        //判断是否修改数据
        $formData = gp();
        if($formData['submits']){
            $inData = array();
            foreach ($formData as $key=>$val) {
                if(array_key_exists($key,$repairItemFirst) && $repairItemFirst[$key] != $val){
                    $inData[$key] = $val;
                }
            }
            //是否默认
            if($inData['isDefault']){
                $this->common_model->update($this->t_pRepairItem, array('isDefault'=>0), array('category'=>$inData['category']));
            }
            //修改自定义维修数据以及基础维修数据
            $updateItem = array();
            if($inData['grade']){
                $updateItem['grade'] = $inData['grade'];
            }
            if($inData['category']){
                $updateItem['category_id'] = $inData['category'];
            }
            if($updateItem){
                $this->common_model->update('mt_base_price',$updateItem,array('labor_id'=>$id));
                $this->common_model->update('mt_customer_price',$updateItem,array('labor_id'=>$id));
            }
            //修改产品信息
            if($inData) {
                $inData['add_user'] = $this->users['account'];
                $inData['add_time'] = time();
                $this->common_model->update($this->t_pRepairItem, $inData, array('id' => $id));
            }
            //修改金额
            $siteList = $this->common_model->selectCustom('mt_service_center');
            foreach ($siteList as $row) {
                $point_id = $row['id'];
                $baseArr = array(
                    'merchant_price'=>$formData['merchant_price'.$point_id],
                    'individual_price'=>$formData['individual_price'.$point_id],
                    'brand_price'=>$formData['brand_price'.$point_id],
                );
                $where = array('site_id'=>$point_id,'labor_id'=>$id);
                $laborFirst = $this->common_model->selectFirst('mt_base_price',$where);
                if($laborFirst){
                    $this->common_model->update('mt_base_price',$baseArr,$where);
                }else{
                    $baseArr['site_id'] = $point_id;
                    $baseArr['labor_id'] = $id;
                    $this->common_model->insert('mt_base_price',$baseArr);
                }
            }
            //调试信息
            if(!$this->debug){
                redirect('orders/Product_repair_item/');
            }
        }else {
            //查询维修等级
            $gradeList = $this->common_model->selectall('mt_repair_grade');
            $data['gradeList'] = $gradeList;
            //查询产品类型
            $categoryList = $this->common_model->selectCustom('mt_product_category');
            $data['categoryList'] = $categoryList;
            //查询SAP大类ID 无视自定义
            $categoryInfo=$this->common_model->selectFirst('mt_product_category',array('id'=>$repairItemFirst['category']));
            $typeId=explode('_',$categoryInfo['sap_id']);
            //查询品牌
            if($repairItemFirst['brand_id']){
                $data['brandList']=$this->productClassData($typeId[0]);
            }
            //查询型号
            if($repairItemFirst['model_id']){
                $data['modelList']=$this->productClassData($typeId[0],$repairItemFirst['brand_id']);
            }
            //获取维修价格
            $sql = 'select a.id as point_id,a.*,b.* from mt_service_center a LEFT JOIN mt_base_price b on a.id = b.site_id  and b.labor_id = '.$id;
            $siteLaborList = $this->common_model->getQuery($sql,'result_array');
            $data['siteLaborList'] = $siteLaborList;
            //default
            $ckdAvailable[$repairItemFirst['available']] = 'checked';
            $data['ckdAvailable'] = $ckdAvailable;
            $ckdIsDefault[$repairItemFirst['isDefault']] = 'checked';
            $data['ckdIsDefault'] = $ckdIsDefault;
            $optGrade[$repairItemFirst['grade']] = 'selected';
            $data['optGrade'] = $optGrade;
            $optCategory[$repairItemFirst['category']] = 'selected';
            $data['optCategory'] = $optCategory;
            $optBrand[$repairItemFirst['brand_id']] = 'selected';
            $data['optBrand'] = $optBrand;
            $optModel[$repairItemFirst['model_id']] = 'selected';
            $data['optModel'] = $optModel;
            //views
            $data['repairItemFirst'] = $repairItemFirst;
            $data['curLang'] = $this->curLang;
            $this->load->view('defaults/product_repairItem_post',$data);
            $this->load->view('defaults/common/footer');
        }
    }


    

    /**
     * 删除
     * @param string $id
     * @param string $page
     */
    function del($id = '',$page = ''){
        $role=$this->users['role_id'];
        $role_array=explode(',',$role);
        if(in_array(1,$role_array)){
            $id = intval($id);
            $this->common_model->delete('mt_product_repair_item',array('id'=>$id));
            $this->common_model->delete('mt_base_price',array('labor_id'=>$id));
            $this->common_model->delete('mt_customer_price',array('labor_id'=>$id));
            redirect(blang_url('orders/Product_repair_item/index/?page='.intval($page)));
        }else{
            show_error('管理员的权限');
        }

    }

    /**
     * 产品分类数据
     * @param string $tid
     * @param string $bid
     * @return string
     */
    function productClassData($tid='',$bid=''){
        if($tid) {
            if ($bid) {
                //查询型号
                $data = $this->sapModel->SapModelList($bid, $tid);
            } else {
                //查询品牌
                $data = $this->sapModel->SapBrandList($tid);
            }
            return $data;
        }else{
            return '';
        }
    }


}
